
#import "GetTorrentListRequest.h"

@implementation GetTorrentListRequest

//
// page index
//
@synthesize pageIndex														= _pageIndex;

//
// torrent list
//
@synthesize torrentList														= _torrentList;

//
// page count
//
@synthesize pageCount														= _pageCount;

//
// filter pattern
//
@synthesize filterPattern													= _filterPattern;

//
// init
//
- (id)init
{
	//
	// call super
	//
	self																	= [super init];
	if(!self)
		return nil;
	
	//
	// init xml parser
	//
	self.xmlParser															= [[[XmlParser alloc] init] autorelease];
	self.torrentList														= [[[NSMutableArray alloc] initWithCapacity:50] autorelease];

	return self;
}

//
// dealloc
//
- (void)dealloc
{
	self.torrentList														= nil;
	self.filterPattern														= nil;
	
	[super dealloc];
}

//
// setup request
//
- (void)setupRequest
{
	//
	// setup rel path
	//
	if(self.filterPattern.length)
		self.relPath														= [NSString stringWithFormat:@"torrents.php?inclbookmarked=0&incldead=0&spstate=0&page=%d&search_mode=0&search_area=0&search=%@", self.pageIndex, [self.filterPattern encodeURL:NSUTF8StringEncoding]];
	else
		self.relPath														= [NSString stringWithFormat:@"torrents.php?inclbookmarked=0&incldead=0&spstate=0&page=%d", self.pageIndex];
	
	//
	// call super
	//
	[super setupRequest];
}

//
// finished
//
- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
	if(self.response.statusCode == 200)
	{
		[self.xmlParser parseDocumentData:self.dataBuffer htmlMode:YES];
		NSString* temp														= [self.xmlParser stringFromPath:@"//td[@id='outer']/table[@class='main']/tr[1]/td[@class='embedded']/p[@align='center']/a[last()]/@href" startNode:0];
		NSRange pageRange													= [temp rangeOfString:@"&page="];
		if(pageRange.location != NSNotFound)
			self.pageCount													= [[temp substringFromIndex:pageRange.location + pageRange.length] integerValue] + 1;
		else
			self.pageCount													= 1;
		
		if(self.pageCount <= self.pageIndex)
			self.pageCount													= self.pageIndex + 1;
		
		NSError* error														= nil;
		NSRegularExpression* regex											= [NSRegularExpression regularExpressionWithPattern:@"^(\\d{4}\\-\\d{2}\\-\\d{2})(\\d{2}:\\d{2}:\\d{2})$" options:NSRegularExpressionAnchorsMatchLines error:&error];
		NSArray* torrentRows												= [self.xmlParser nodesFromPath:@"//table[@class='torrents']/tr[position()>1]" startNode:nil];
		NSString* sizeXPath													= nil;
		NSString* uploadDateXPath1											= nil;
		NSString* uploadDateXPath2											= nil;
		NSString* seederXPath												= nil;
		NSString* leecherXPath												= nil;
		NSString* uploaderXPath1											= nil;
		NSString* uploaderXPath2											= nil;
		NSString* uploaderIdXPath											= nil;
		for(NSValue* rowValue in torrentRows)
		{
			//
			// detect cell count
			//
			xmlNodePtr xmlRow												= (xmlNodePtr)[rowValue pointerValue];
			if(!sizeXPath || !uploadDateXPath1 || !uploadDateXPath2)
			{
				NSString* tdClass											= [self.xmlParser stringFromPath:@"./td[3]/@class" startNode:xmlRow];
				NSInteger commentIndex										= [tdClass isEqualToString:@"rowfollow"] ? 3 : 2;
				uploadDateXPath1											= [NSString stringWithFormat:@"./td[%d]/span/@title", commentIndex + 1];
				uploadDateXPath2											= [NSString stringWithFormat:@"./td[%d]", commentIndex + 1];
				sizeXPath													= [NSString stringWithFormat:@"./td[%d]", commentIndex + 2];
				seederXPath													= [NSString stringWithFormat:@"./td[%d]/b/a", commentIndex + 3];
				leecherXPath												= [NSString stringWithFormat:@"./td[%d]/b/a", commentIndex + 4];
				uploaderXPath1												= [NSString stringWithFormat:@"./td[%d]/span/a/b", commentIndex + 6];
				uploaderXPath2												= [NSString stringWithFormat:@"./td[%d]", commentIndex + 6];
				uploaderIdXPath												= [NSString stringWithFormat:@"./td[%d]/span/a/@href", commentIndex + 6];
			}
			
			//
			// parse torrent info
			//
			@autoreleasepool
			{
				TorrentInfo* info											= [[[TorrentInfo alloc] init] autorelease];
				info.unread													= YES;
				info.sticky													= [self.xmlParser nodeFromPath:@"./td[2]/table/tr[1]/td[1]/img[@class='sticky']" startNode:xmlRow] ? YES : NO;
				info.category												= [self.xmlParser stringFromPath:@"./td[1]/a" startNode:xmlRow];
				NSString* temp												= [self.xmlParser stringFromPath:@"./td[2]/table/tr[1]/td[1]/a[1]/@href" startNode:xmlRow];
				info.torrentId												= [[temp substringWithRange:NSMakeRange(15, temp.length - 15 - 6)] integerValue];
				info.title													= [self.xmlParser stringFromPath:@"./td[2]/table/tr[1]/td[1]/a[1]/@title" startNode:xmlRow];
				info.size													= [self.xmlParser stringFromPath:sizeXPath startNode:xmlRow];
				info.uploadDate												= [self.xmlParser stringFromPath:uploadDateXPath1 startNode:xmlRow];
				if(!info.uploadDate)
				{
					temp													= [self.xmlParser stringFromPath:uploadDateXPath2 startNode:xmlRow];
					NSTextCheckingResult* match								= !temp.length || error || !regex ? nil : [regex firstMatchInString:temp options:0 range:NSMakeRange(0, temp.length)];
					if(match)
						info.uploadDate										= [NSString stringWithFormat:@"%@ %@", [temp substringWithRange:[match rangeAtIndex:1]], [temp substringWithRange:[match rangeAtIndex:2]]];
				}
				info.seederCount											= [[self.xmlParser stringFromPath:seederXPath startNode:xmlRow] integerValue];
				info.leecherCount											= [[self.xmlParser stringFromPath:leecherXPath startNode:xmlRow] integerValue];
				info.magicExpire											= [self.xmlParser stringFromPath:@"./td[2]/table/tr[1]/td[1]/b[last()]/span/@title" startNode:xmlRow];
				info.upRate													= [self.xmlParser stringFromPath:@"./td[2]/table/tr[1]/td[1]/img[@class='arrowup']/following-sibling::b[1]" startNode:xmlRow];
				info.downRate												= [self.xmlParser stringFromPath:@"./td[2]/table/tr[1]/td[1]/img[@class='arrowdown']/following-sibling::b[1]" startNode:xmlRow];
				if(!info.upRate && !info.downRate)
				{
					info.upRate												= [NexusClient parseFreeTypeForImgClass:[self.xmlParser stringFromPath:@"./td[2]/table/tr[1]/td[1]/img[@class!='sticky' and @class!='arrowup' and @class!='arrowdown']/@class" startNode:xmlRow]];
					if(!info.upRate && info.magicExpire)
						info.upRate											= [NexusClient parseFreeTypeForFontClass:[self.xmlParser stringFromPath:@"./td[2]/table/tr[1]/td[1]/b[last()-1]/font/@class" startNode:xmlRow]];
					if(!info.upRate)
						info.upRate											= [NexusClient parseFreeTypeForFontClass:[self.xmlParser stringFromPath:@"./td[2]/table/tr[1]/td[1]/b[last()]/font/@class" startNode:xmlRow]];
					if(!info.upRate)
						info.upRate											= [NexusClient parseFreeTypeForRowClass:[self.xmlParser stringFromPath:@"./td[2]/table/tr[1]/@class" startNode:xmlRow]];
				}
				
				//
				// add to list
				//
				[self.torrentList addObject:info];
			}
		}
	}
	
	[super connectionDidFinishLoading:connection];
}

@end
